//
//  DJPopMenuView.m
//  WeiboDemo
//
//  Created by Bworm on 15/1/30.
//  Copyright (c) 2015年 Bworm. All rights reserved.
//

#import "DJPopMenuView.h"

@implementation DJPopMenuView

UIWindow *_window;
dismissBlock _dismiss;

+ (void)popFrom:(UIView *)fromView content:(UIView *)content dismiss:(dismissBlock)dismiss
{
    [self popFrom:fromView.frame inView:fromView.superview content:content dismiss:dismiss];
}

+ (void)popFrom:(CGRect)fromRect inView:(UIView *)inView content:(UIView *)content dismiss:(dismissBlock)dismiss
{
    _dismiss = [dismiss copy];
    
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.hidden = NO;
    _window.windowLevel = UIWindowLevelAlert;
    
    UIButton *cover = [[UIButton alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [cover setBackgroundColor:[UIColor clearColor]];
    
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    [_window addSubview:cover];
    
    // 创建容器来显示content
    UIImageView *menuView = [[UIImageView alloc] init];
    menuView.userInteractionEnabled = YES;
    UIImage *image = [UIImage imageNamed:@"popover_background"];
    menuView.image = image;
    [cover addSubview:menuView];
    
    // 设置tableView在menuVc中显示的范围,设置间距
    content.x = 15;
    content.y = 18;
    [menuView addSubview:content];
    
    CGFloat menuViewW = CGRectGetMaxX(content.frame) + content.x;
    CGFloat menuViewH = CGRectGetMaxY(content.frame) + content.y;
    menuView.frame = CGRectMake(0, 0, menuViewW, menuViewH);
    
    CGRect resultFrame = [_window convertRect:fromRect fromView:inView];
    
    menuView.y = CGRectGetMaxY(resultFrame) + 3;
    
//    CGPoint resultCenter = [_window convertPoint:fromView.center fromView:fromView.superview];
    
    menuView.centerX = resultFrame.origin.x + (resultFrame.size.width * 0.5);

}

UIViewController *_contentVC;
+ (void)popFrom:(UIView *)fromView contentVc:(UIViewController *)contentVc dismiss:(dismissBlock)dismiss
{
    _contentVC = contentVc;
    
    [self popFrom:fromView content:_contentVC.view dismiss:dismiss];
}

+ (void)coverClick:(UIButton *)btn
{
    _window = nil;
    if (_dismiss != nil) {
        _dismiss();
    }
}
@end
